package jjsan.callback.phone;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.util.Locale;

import jjsan.callback.BaseActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
//import android.widget.Toast;
/**
 * Configuration screen for the camera button 
 * @author tedd
 *
 */

public class ConfigScreenActivity extends BaseActivity {

	 public static final String PREFS_NAME = "MyPrefsFile";
	
    /** Called when the activity is first created. */
	 
	 @Override
	 public void onConfigurationChanged(Configuration newConfig) {
	   // refresh your views here
	   super.onConfigurationChanged(newConfig);
	   
	 }

	 
	public void SetLanguage()
	{
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        
        //is callback enabled?
        //boolean callback_enabled = settings.getBoolean("callback_enabled", true);
        //get pause time
        //int PREF_PAUSE_TIME = settings.getInt("pause_time", 0);
        //get language
        int PREF_LANGUAGE = settings.getInt("language", 0);
         
	
        //set language
    	Locale locale2;        
    	
    	//change langauge to selected
    	switch (PREF_LANGUAGE) {
    	case 1: locale2 = new Locale("sk");
    	case 2: locale2 = new Locale("cs"); 
    	case 3: locale2 = new Locale("fr"); 
    	case 4: locale2 = new Locale("de");
    	default:locale2 = new Locale("en");
    	}
    	
    	locale2 = new Locale("cs");
    	
    	Locale.setDefault(locale2);
        Configuration config2 = new Configuration();
        config2.locale = locale2;
        Locale.setDefault(locale2);
        getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics());
	}
	 
	public void DrawElements()
	{
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        
        
        //is callback enabled?
        boolean callback_enabled = settings.getBoolean("callback_enabled", true);
        //get pause time
        int PREF_PAUSE_TIME = settings.getInt("pause_time", 0);
        //get language
        int PREF_LANGUAGE = settings.getInt("language", 0);
         
        //render checkbox with pause settings
        renderConfigCheckbox(Hc.PREF_PHONE_TOOLS_KEY,callback_enabled,R.id.phoneToolsCheckBox,getString(R.string.callback_main_toast));
        
        //draw a listbox for pause
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.time_array, android.R.layout.simple_spinner_item);
        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(PREF_PAUSE_TIME);
        spinner.setOnItemSelectedListener(new TimeSpinnerChange());

        //draw a listbox for language
        Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
                this, R.array.language_array, android.R.layout.simple_spinner_item);
        
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);
        spinner2.setSelection(PREF_LANGUAGE);
        spinner2.setOnItemSelectedListener(new LanguageSpinnerChange());
        
        Button btnCheckUpdate = (Button) findViewById(R.id.btnCheckUpdate);
			btnCheckUpdate.setOnClickListener(new CheckUpdateClicked());
		
  
	}
	 
	
	public final boolean isInternetOn() {
		ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		// ARE WE CONNECTED TO THE NET
		if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
		connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
		connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
		connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
		// MESSAGE TO SCREEN FOR TESTING (IF REQ)
		//Toast.makeText(this, " connected", Toast.LENGTH_SHORT).show();
		return true;
		} else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) {
		//System.out.println("Not Connected");
		return false;
		}
		return false;
		}
	
	public class CheckUpdateClicked implements OnClickListener {
		@Override
		
		public void onClick(View v) {
			String onlineVersion = null;
			//String installedVersion = null;
			
			if(isInternetOn()) {
		     	
			try {

			      URL url = new URL("http://www.jjsan.eu/android/version.txt");

			      // Obtain output stream
			      DataInputStream dis = new DataInputStream(new BufferedInputStream(url.openStream()));
			      
			      
			      onlineVersion = dis.readLine();

				} catch (Exception e) {
			    	//Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
					
			    }
				
				String strVersion;
				  
				   PackageInfo packageInfo;
				   try {
				    packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
				    strVersion = packageInfo.versionName;
				   } catch (NameNotFoundException e) {
				    e.printStackTrace();
				    strVersion = "Cannot load Version!";
				   } 
				   
				   ////Toast.makeText(getApplicationContext(), onlineVersion , Toast.LENGTH_SHORT).show();
				
				   
				   AlertDialog alertDialog = new AlertDialog.Builder(ConfigScreenActivity.this).create();
				   alertDialog.setTitle(getString(R.string.versoion_check));
				   
				   if (onlineVersion.equals(strVersion)){
				   alertDialog.setMessage(getString(R.string.last_installed));
				   }
				   else
				   {
				   alertDialog.setMessage(getString(R.string.new_version) + onlineVersion);
				   }
				   
				   alertDialog.setButton(getString(R.string.btnOK), new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				         // here you can add functions
				      }
				   });
				   alertDialog.setIcon(R.drawable.icon);
				   alertDialog.show();
			}
			else
			{
				   AlertDialog alertDialog = new AlertDialog.Builder(ConfigScreenActivity.this).create();
				   alertDialog.setTitle(getString(R.string.versoion_check));
				   alertDialog.setMessage(getString(R.string.noConnection));
				   alertDialog.setButton(getString(R.string.btnOK), new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				         // here you can add functions
				      }
				   });
				   alertDialog.setIcon(R.drawable.icon);
				   alertDialog.show();
				}
			
		}
	}

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //SetLanguage();
        
        
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        
        //get language - default english
        int PREF_LANGUAGE = settings.getInt("language", 0);
        //set language
    	//default en
        String tmp="en";        
    	
    	//change langauge to selected
    	if (PREF_LANGUAGE==1) tmp = "sk";
    	if (PREF_LANGUAGE==2) tmp = "cs";	
    	if (PREF_LANGUAGE==3) tmp = "fr";
    	if (PREF_LANGUAGE==4) tmp = "de";
    	
    	Locale locale2 = new Locale(tmp);
    	
    	Locale.setDefault(locale2);
        Configuration config2 = new Configuration();
        config2.locale = locale2;
        Locale.setDefault(locale2);
        getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics());
        
        setContentView(R.layout.main);

        DrawElements();
        
    }
    
    private void renderConfigCheckbox(String key,boolean defaultVal,int viewId, String toastMsg) {
    	// set the default if it didn't exist
        if (!p.contains(key))
        	p.edit().putBoolean(key, defaultVal).commit();

        // get the current setting
        Boolean currentSetting = p.getBoolean(key, defaultVal);
        
        // get the view component
        final CheckBox checkbox = (CheckBox) findViewById(viewId);
        
        // set the current setting
        checkbox.setChecked(currentSetting);
        
        // register the onClick call back
        checkbox.setOnClickListener(new CustomOnClickListener(key,toastMsg) {
            public void onClick(View v) {
            	// Commit the edits!
            	p.edit().putBoolean("callback_enabled", ((CheckBox) v).isChecked()).commit();
                            
            	if (((CheckBox) v).isChecked()) 
                {
                	p.edit().putBoolean(key, true).commit();
                    //Toast.makeText(ConfigScreenActivity.this, toastMsg + " "+getString(R.string.callback_main_toast_ena), Toast.LENGTH_SHORT).show();
                } 
                else 
                {
                	p.edit().putBoolean(key, false).commit();
                    //Toast.makeText(ConfigScreenActivity.this, toastMsg + " "+getString(R.string.callback_main_toast_dis), Toast.LENGTH_SHORT).show();
                }
            }
        });  
        
}
    
    
    private class CustomOnClickListener implements OnClickListener {

    	protected String key;
    	@SuppressWarnings("unused")
		protected String toastMsg;
    	public CustomOnClickListener(String key,String toastMsg) {
    		this.key = key; 
    		this.toastMsg = toastMsg;
    	}
		@Override
		public void onClick(View v) {
			throw new UnsupportedOperationException();
			
		}
    	
    }    
}